package io.terminus.paas.profiler.registry

import com.alibaba.dubbo.common.URL
import com.alibaba.dubbo.common.utils.UrlUtils
import com.alibaba.dubbo.registry.RegistryService
import com.alibaba.dubbo.registry.zookeeper.ZookeeperRegistry
import com.alibaba.dubbo.remoting.zookeeper.zkclient.ZkclientZookeeperTransporter
import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import io.terminus.paas.profiler.utils.RegistryServerSync
import org.springframework.stereotype.Service

/**
 * Created by gengrong on 16/4/11.
 */
@Service
class RegistryServiceRouter {

    //TODO 缓存策略 size等还需调整
    private val registryServiceCacheLoader = object : CacheLoader<URL, RegistryService>() {
        override fun load(url: URL): RegistryService {
            val registryService = when (url.protocol.toLowerCase()) {
                "zookeeper" -> ZookeeperRegistry(url, ZkclientZookeeperTransporter())
                else -> throw IllegalArgumentException("unsupported protocol")
            }
            return registryService
        }
    }

    private val registryServiceCache = CacheBuilder.newBuilder().build(registryServiceCacheLoader)

    private val registryServerSyncCacheLoader = object : CacheLoader<String, RegistryServerSync>() {
        override fun load(registryAddress: String): RegistryServerSync {
            val registryService = getInstance(registryAddress)
            val registryServerSync = RegistryServerSync(registryService)
            return registryServerSync
        }
    }

    private val registryServerSyncCache = CacheBuilder.newBuilder().build(registryServerSyncCacheLoader)

    fun getInstance(registryAddress: String): RegistryService {
        val url = UrlUtils.parseURL(registryAddress, null)
        return registryServiceCache.get(url)
    }

    fun getRegistryServerSync(registryAddress: String): RegistryServerSync {
        return registryServerSyncCache.get(registryAddress)
    }

}